/**
 * 健康床监控系统数据调试工具
 * 用于分析和诊断数据流问题
 */
const dataDebugger = {
    // 数据历史记录
    history: [],
    
    // 最大历史记录数
    maxHistory: 10,
    
    // 期望的物模型字段
    expectedFields: ['radar_heartrate', 'radar_breath', 'temp', 'humidity'],
    
    // 处理API响应
    processResponse: function(response, isTestData = false) {
        console.log('数据调试工具开始处理数据:', isTestData ? '测试数据' : '实际数据');
        
        // 添加到历史记录
        this.addToHistory(response, isTestData);
        
        // 提取有效数据
        const validData = this.extractValidData(response);
        console.log('提取的有效数据:', validData);
        
        // 分析数据结构
        const analysis = this.analyzeDataStructure(response);
        console.log('数据结构分析:', analysis);
        
        // 诊断数据问题
        const diagnostics = this.diagnoseData(response, validData);
        console.log('数据诊断结果:', diagnostics);
        
        // 如果存在调试UI，更新显示
        if (typeof this.updateDebugPanel === 'function') {
            this.updateDebugPanel(validData, analysis, diagnostics);
        }
        
        return {
            validData: validData,
            analysis: analysis,
            diagnostics: diagnostics
        };
    },
    
    // 添加数据到历史记录
    addToHistory: function(data, isTestData) {
        this.history.unshift({
            timestamp: new Date(),
            data: JSON.parse(JSON.stringify(data)),
            isTestData: isTestData
        });
        
        // 限制历史记录大小
        if (this.history.length > this.maxHistory) {
            this.history = this.history.slice(0, this.maxHistory);
        }
    },
    
    // 提取有效数据
    extractValidData: function(data) {
        const result = {
            vitals: {},
            environment: {}
        };
        
        // 检查物模型格式
        if (data && data.Data && data.Data.List && data.Data.List.PropertyStatusInfo) {
            console.log('检测到物模型格式数据');
            const properties = data.Data.List.PropertyStatusInfo;
            
            properties.forEach(prop => {
                const identifier = prop.Identifier;
                const value = prop.Value;
                
                // 人体数据
                if (identifier === 'radar_heartrate') {
                    result.vitals.heartRate = this.parseValue(value);
                    console.log('提取心率数据:', value, '→', result.vitals.heartRate);
                } else if (identifier === 'radar_breath') {
                    result.vitals.breathRate = this.parseValue(value);
                    console.log('提取呼吸率数据:', value, '→', result.vitals.breathRate);
                }
                // 环境数据
                else if (identifier === 'temp') {
                    result.environment.temperature = this.parseValue(value);
                    console.log('提取温度数据:', value, '→', result.environment.temperature);
                } else if (identifier === 'humidity') {
                    result.environment.humidity = this.parseValue(value);
                    console.log('提取湿度数据:', value, '→', result.environment.humidity);
                }
            });
        }
        // 检查传统格式 - 正确的设备名称是 device1 而不是 Spark
        else if (data && data.devices && data.devices.device1) {
            console.log('检测到传统格式数据');
            const deviceData = data.devices.device1;
            
            // 尝试匹配多种可能的字段名
            result.vitals.heartRate = this.parseValue(
                deviceData.radar_heartrate !== undefined ? deviceData.radar_heartrate : 
                deviceData.heart_rate !== undefined ? deviceData.heart_rate : null
            );
            console.log('提取心率数据:', deviceData.radar_heartrate || deviceData.heart_rate, '→', result.vitals.heartRate);
            
            result.vitals.breathRate = this.parseValue(
                deviceData.radar_breath !== undefined ? deviceData.radar_breath : 
                deviceData.breath_rate !== undefined ? deviceData.breath_rate : null
            );
            console.log('提取呼吸率数据:', deviceData.radar_breath || deviceData.breath_rate, '→', result.vitals.breathRate);
            
            result.environment.temperature = this.parseValue(
                deviceData.temp !== undefined ? deviceData.temp : 
                deviceData.temperature !== undefined ? deviceData.temperature : null
            );
            console.log('提取温度数据:', deviceData.temp || deviceData.temperature, '→', result.environment.temperature);
            
            result.environment.humidity = this.parseValue(
                deviceData.humidity
            );
            console.log('提取湿度数据:', deviceData.humidity, '→', result.environment.humidity);
        }
        // 备用格式 - 检查traditional_format
        else if (data && data.traditional_format && data.traditional_format.devices && data.traditional_format.devices.device1) {
            console.log('检测到备用格式数据 (traditional_format)');
            const deviceData = data.traditional_format.devices.device1;
            
            result.vitals.heartRate = this.parseValue(deviceData.heart_rate);
            console.log('提取心率数据:', deviceData.heart_rate, '→', result.vitals.heartRate);
            
            result.vitals.breathRate = this.parseValue(deviceData.breath_rate);
            console.log('提取呼吸率数据:', deviceData.breath_rate, '→', result.vitals.breathRate);
            
            result.environment.temperature = this.parseValue(deviceData.temperature);
            console.log('提取温度数据:', deviceData.temperature, '→', result.environment.temperature);
            
            result.environment.humidity = this.parseValue(deviceData.humidity);
            console.log('提取湿度数据:', deviceData.humidity, '→', result.environment.humidity);
        } else {
            console.warn('未识别的数据格式:', data ? Object.keys(data).join(', ') : 'null');
        }
        
        return result;
    },
    
    // 安全解析值
    parseValue: function(value) {
        if (value === null || value === undefined) return null;
        
        // 尝试转换为数字
        if (typeof value === 'string') {
            const num = Number(value);
            if (!isNaN(num)) return num;
        }
        else if (typeof value === 'number') {
            return value;
        }
        
        // 对于非数字类型，如果是0或"0"，返回数字0
        if (value === 0 || value === '0') return 0;
        
        // 返回原始值
        return value;
    },
    
    // 分析数据结构
    analyzeDataStructure: function(data) {
        const analysis = {
            dataFormat: 'unknown',
            detectedFields: [],
            missingFields: [],
            dataQuality: 'unknown',
            dataSource: 'unknown',
            timestamp: null,
            hasDeviceData: false
        };
        
        // 检查物模型格式
        if (data && data.Data && data.Data.List && data.Data.List.PropertyStatusInfo) {
            analysis.dataFormat = 'property_model';
            analysis.dataSource = 'Spark设备物模型数据';
            const properties = data.Data.List.PropertyStatusInfo;
            
            // 收集检测到的字段
            analysis.detectedFields = properties.map(p => p.Identifier);
            
            // 记录时间戳
            if (data.metadata && data.metadata.timestamp) {
                analysis.timestamp = data.metadata.timestamp;
            }
            
            analysis.hasDeviceData = true;
        }
        // 检查传统格式
        else if (data && data.devices && data.devices.device1) {
            analysis.dataFormat = 'traditional';
            analysis.dataSource = 'Spark设备传统格式数据';
            const deviceData = data.devices.device1;
            
            // 收集检测到的字段
            analysis.detectedFields = Object.keys(deviceData);
            
            // 记录时间戳
            if (data.timestamp) {
                analysis.timestamp = data.timestamp;
            } else if (deviceData.timestamp) {
                analysis.timestamp = deviceData.timestamp;
            }
            
            analysis.hasDeviceData = true;
        }
        // 检查备用格式
        else if (data && data.traditional_format && data.traditional_format.devices && data.traditional_format.devices.device1) {
            analysis.dataFormat = 'traditional_format';
            analysis.dataSource = 'Spark设备备用格式数据';
            const deviceData = data.traditional_format.devices.device1;
            
            // 收集检测到的字段
            analysis.detectedFields = Object.keys(deviceData);
            
            // 记录时间戳
            if (data.traditional_format.timestamp) {
                analysis.timestamp = data.traditional_format.timestamp;
            } else if (deviceData.timestamp) {
                analysis.timestamp = deviceData.timestamp;
            }
            
            analysis.hasDeviceData = true;
        }
        
        // 检查期望的字段是否存在
        let effectiveFields = [...analysis.detectedFields];
        
        // 添加字段映射检查
        if (analysis.detectedFields.includes('heart_rate') && !analysis.detectedFields.includes('radar_heartrate')) {
            effectiveFields.push('radar_heartrate');
        }
        if (analysis.detectedFields.includes('breath_rate') && !analysis.detectedFields.includes('radar_breath')) {
            effectiveFields.push('radar_breath');
        }
        if (analysis.detectedFields.includes('temperature') && !analysis.detectedFields.includes('temp')) {
            effectiveFields.push('temp');
        }
        
        analysis.missingFields = this.expectedFields.filter(field => 
            !effectiveFields.includes(field)
        );
        
        // 评估数据质量
        if (!analysis.hasDeviceData) {
            analysis.dataQuality = 'missing';
        } else if (analysis.missingFields.length === 0) {
            analysis.dataQuality = 'excellent';
        } else if (analysis.missingFields.length < this.expectedFields.length / 2) {
            analysis.dataQuality = 'good';
        } else {
            analysis.dataQuality = 'poor';
        }
        
        return analysis;
    },
    
    // 诊断数据问题
    diagnoseData: function(data, validData) {
        const diagnostics = {
            issues: [],
            recommendations: [],
            details: {}
        };
        
        // 如果数据为空或不是对象
        if (!data || typeof data !== 'object') {
            diagnostics.issues.push('数据为空或格式无效');
            diagnostics.recommendations.push('检查API返回数据是否正确');
            return diagnostics;
        }
        
        // 检查API响应结构
        if (!data.Data && !data.devices && !data.traditional_format) {
            diagnostics.issues.push('API响应缺少关键数据结构');
            diagnostics.recommendations.push('API响应需要包含Data(物模型)或devices(传统)字段');
            diagnostics.details.apiStructure = {
                hasData: !!data.Data,
                hasDevices: !!data.devices,
                hasTraditionalFormat: !!data.traditional_format,
                topLevelFields: Object.keys(data)
            };
        }
        
        // 检查人体数据
        if (validData.vitals) {
            diagnostics.details.vitals = {
                heartRate: validData.vitals.heartRate,
                breathRate: validData.vitals.breathRate
            };
            
            if (validData.vitals.heartRate === null || validData.vitals.heartRate === undefined) {
                diagnostics.issues.push('心率数据缺失');
                diagnostics.recommendations.push('检查设备是否上报心率数据');
            } else if (validData.vitals.heartRate === 0) {
                diagnostics.issues.push('心率数据为0');
                diagnostics.recommendations.push('验证设备传感器是否正常工作');
            } else if (validData.vitals.heartRate < 40 || validData.vitals.heartRate > 200) {
                diagnostics.issues.push(`心率数据异常(${validData.vitals.heartRate})`);
                diagnostics.recommendations.push('检查心率数据是否在合理范围(40-200)');
            }
            
            if (validData.vitals.breathRate === null || validData.vitals.breathRate === undefined) {
                diagnostics.issues.push('呼吸率数据缺失');
                diagnostics.recommendations.push('检查设备是否上报呼吸率数据');
            } else if (validData.vitals.breathRate === 0) {
                diagnostics.issues.push('呼吸率数据为0');
                diagnostics.recommendations.push('验证设备传感器是否正常工作');
            } else if (validData.vitals.breathRate < 5 || validData.vitals.breathRate > 40) {
                diagnostics.issues.push(`呼吸率数据异常(${validData.vitals.breathRate})`);
                diagnostics.recommendations.push('检查呼吸率数据是否在合理范围(5-40)');
            }
        } else {
            diagnostics.issues.push('未能提取生命体征数据');
            diagnostics.recommendations.push('检查生命体征数据字段名是否符合预期');
        }
        
        // 检查环境数据
        if (validData.environment) {
            diagnostics.details.environment = {
                temperature: validData.environment.temperature,
                humidity: validData.environment.humidity
            };
            
            if (validData.environment.temperature === null || validData.environment.temperature === undefined) {
                diagnostics.issues.push('温度数据缺失');
                diagnostics.recommendations.push('检查设备是否上报温度数据');
            } else if (validData.environment.temperature === 0) {
                diagnostics.issues.push('温度数据为0');
                diagnostics.recommendations.push('验证温度传感器是否正常工作');
            } else if (validData.environment.temperature < -20 || validData.environment.temperature > 50) {
                diagnostics.issues.push(`温度数据异常(${validData.environment.temperature})`);
                diagnostics.recommendations.push('检查温度数据是否在合理范围(-20~50℃)');
            }
            
            if (validData.environment.humidity === null || validData.environment.humidity === undefined) {
                diagnostics.issues.push('湿度数据缺失');
                diagnostics.recommendations.push('检查设备是否上报湿度数据');
            } else if (validData.environment.humidity === 0) {
                diagnostics.issues.push('湿度数据为0');
                diagnostics.recommendations.push('验证湿度传感器是否正常工作');
            } else if (validData.environment.humidity < 0 || validData.environment.humidity > 100) {
                diagnostics.issues.push(`湿度数据异常(${validData.environment.humidity})`);
                diagnostics.recommendations.push('检查湿度数据是否在合理范围(0-100%)');
            }
        } else {
            diagnostics.issues.push('未能提取环境数据');
            diagnostics.recommendations.push('检查环境数据字段名是否符合预期');
        }
        
        return diagnostics;
    },
    
    // 更新调试面板
    updateDebugPanel: function(validData, analysis, diagnostics) {
        // 创建或更新调试面板
        let debugPanel = document.getElementById('data-debug-panel');
        if (!debugPanel) {
            debugPanel = document.createElement('div');
            debugPanel.id = 'data-debug-panel';
            debugPanel.style.position = 'fixed';
            debugPanel.style.bottom = '0';
            debugPanel.style.left = '0';
            debugPanel.style.right = '0';
            debugPanel.style.background = 'rgba(0,0,0,0.8)';
            debugPanel.style.color = 'white';
            debugPanel.style.padding = '10px';
            debugPanel.style.zIndex = '1000';
            debugPanel.style.fontFamily = 'monospace';
            debugPanel.style.maxHeight = '70vh';
            debugPanel.style.overflowY = 'auto';
            
            // 添加关闭按钮
            const closeBtn = document.createElement('button');
            closeBtn.innerText = '关闭';
            closeBtn.style.position = 'absolute';
            closeBtn.style.top = '10px';
            closeBtn.style.right = '10px';
            closeBtn.style.padding = '5px 10px';
            closeBtn.style.background = '#ff5a5f';
            closeBtn.style.color = 'white';
            closeBtn.style.border = 'none';
            closeBtn.style.borderRadius = '3px';
            closeBtn.style.cursor = 'pointer';
            closeBtn.onclick = function() {
                debugPanel.style.display = 'none';
            };
            debugPanel.appendChild(closeBtn);
            
            document.body.appendChild(debugPanel);
        }
        
        // 格式化时间
        const formattedTime = new Date().toLocaleTimeString();
        
        // 更新面板内容
        debugPanel.innerHTML = `
            <div style="position: relative; padding-right: 100px;">
                <h3>数据调试面板 <span style="font-size: 12px; color: #aaa;">${formattedTime}</span></h3>
                <button id="debugPanelCloseBtn" style="position: absolute; top: 5px; right: 10px; padding: 5px 10px; background: #ff5a5f; color: white; border: none; border-radius: 3px; cursor: pointer;">关闭</button>
            </div>
            
            <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                <div style="flex: 1; min-width: 300px;">
                    <h4>有效数据</h4>
                    <div style="background: #111; padding: 10px; border-radius: 5px;">
                        <div>
                            <strong>生命体征:</strong>
                            <ul>
                                <li>心率: <span style="color: ${validData.vitals.heartRate ? '#4caf50' : '#ff5a5f'}">${validData.vitals.heartRate !== null ? validData.vitals.heartRate : '缺失'}</span></li>
                                <li>呼吸率: <span style="color: ${validData.vitals.breathRate ? '#4caf50' : '#ff5a5f'}">${validData.vitals.breathRate !== null ? validData.vitals.breathRate : '缺失'}</span></li>
                            </ul>
                        </div>
                        <div>
                            <strong>环境数据:</strong>
                            <ul>
                                <li>温度: <span style="color: ${validData.environment.temperature ? '#4caf50' : '#ff5a5f'}">${validData.environment.temperature !== null ? validData.environment.temperature : '缺失'}</span></li>
                                <li>湿度: <span style="color: ${validData.environment.humidity ? '#4caf50' : '#ff5a5f'}">${validData.environment.humidity !== null ? validData.environment.humidity : '缺失'}</span></li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <div style="flex: 1; min-width: 300px;">
                    <h4>数据分析</h4>
                    <div style="background: #111; padding: 10px; border-radius: 5px;">
                        <p><strong>数据格式:</strong> <span style="color: #4caf50;">${analysis.dataFormat}</span></p>
                        <p><strong>数据源:</strong> <span>${analysis.dataSource}</span></p>
                        <p><strong>数据质量:</strong> <span style="color: ${
                            analysis.dataQuality === 'excellent' ? '#4caf50' : 
                            analysis.dataQuality === 'good' ? '#ffeb3b' : 
                            analysis.dataQuality === 'poor' ? '#ff9800' : '#ff5a5f'
                        };">${analysis.dataQuality}</span></p>
                        <p><strong>时间戳:</strong> <span>${analysis.timestamp || '未知'}</span></p>
                        <p><strong>检测字段:</strong> <span>${analysis.detectedFields.join(', ') || '无'}</span></p>
                        <p><strong>缺失字段:</strong> <span style="color: ${analysis.missingFields.length ? '#ff9800' : '#4caf50'}">${analysis.missingFields.join(', ') || '无'}</span></p>
                    </div>
                </div>
                
                <div style="flex: 1; min-width: 300px;">
                    <h4>问题诊断</h4>
                    <div style="background: #111; padding: 10px; border-radius: 5px;">
                        ${diagnostics.issues.length > 0 ? 
                            `<div>
                                <strong style="color: #ff5a5f;">发现问题:</strong>
                                <ul style="color: #ff9800;">
                                    ${diagnostics.issues.map(issue => `<li>${issue}</li>`).join('')}
                                </ul>
                            </div>` : 
                            '<p style="color: #4caf50;">✓ 未发现问题</p>'}
                        ${diagnostics.recommendations.length > 0 ? 
                            `<div>
                                <strong>建议:</strong>
                                <ul style="color: #2196f3;">
                                    ${diagnostics.recommendations.map(rec => `<li>${rec}</li>`).join('')}
                                </ul>
                            </div>` : 
                            ''}
                    </div>
                </div>
            </div>
            
            <div style="margin-top: 15px;">
                <button id="debugPanelCopyBtn" style="padding: 5px 10px; background: #2196f3; color: white; border: none; border-radius: 3px; cursor: pointer; margin-right: 10px;">复制诊断结果</button>
                <button id="debugPanelToggleRawBtn" style="padding: 5px 10px; background: #673ab7; color: white; border: none; border-radius: 3px; cursor: pointer;">查看原始数据</button>
                <div id="debugPanelRawData" style="display: none; margin-top: 10px; background: #111; padding: 10px; border-radius: 5px; max-height: 200px; overflow: auto;">
                    <pre>${JSON.stringify(this.history[0]?.data || {}, null, 2)}</pre>
                </div>
            </div>
        `;
        
        // 添加事件监听器
        document.getElementById('debugPanelCloseBtn').onclick = function() {
            debugPanel.style.display = 'none';
        };
        
        document.getElementById('debugPanelCopyBtn').onclick = function() {
            const diagnosticText = `
数据调试报告 (${new Date().toLocaleString()})
-----------------------------
数据格式: ${analysis.dataFormat}
数据源: ${analysis.dataSource}
数据质量: ${analysis.dataQuality}
时间戳: ${analysis.timestamp || '未知'}

有效数据:
- 心率: ${validData.vitals.heartRate !== null ? validData.vitals.heartRate : '缺失'}
- 呼吸率: ${validData.vitals.breathRate !== null ? validData.vitals.breathRate : '缺失'}
- 温度: ${validData.environment.temperature !== null ? validData.environment.temperature : '缺失'}
- 湿度: ${validData.environment.humidity !== null ? validData.environment.humidity : '缺失'}

检测字段: ${analysis.detectedFields.join(', ') || '无'}
缺失字段: ${analysis.missingFields.join(', ') || '无'}

诊断问题:
${diagnostics.issues.length > 0 ? diagnostics.issues.map(issue => `- ${issue}`).join('\n') : '✓ 未发现问题'}

建议:
${diagnostics.recommendations.length > 0 ? diagnostics.recommendations.map(rec => `- ${rec}`).join('\n') : '✓ 无需额外操作'}
            `;
            
            navigator.clipboard.writeText(diagnosticText).then(function() {
                alert('诊断结果已复制到剪贴板');
            }, function() {
                alert('复制失败，请手动复制');
            });
        };
        
        document.getElementById('debugPanelToggleRawBtn').onclick = function() {
            const rawDataDiv = document.getElementById('debugPanelRawData');
            rawDataDiv.style.display = rawDataDiv.style.display === 'none' ? 'block' : 'none';
        };
    },
    
    // 显示调试面板
    showDebugPanel: function() {
        const debugPanel = document.getElementById('data-debug-panel');
        if (debugPanel) {
            debugPanel.style.display = 'block';
        } else {
            console.warn('调试面板未初始化，请先处理数据');
        }
    },
    
    // 隐藏调试面板
    hideDebugPanel: function() {
        const debugPanel = document.getElementById('data-debug-panel');
        if (debugPanel) {
            debugPanel.style.display = 'none';
        }
    }
};

// 导出模块
window.dataDebugger = dataDebugger;
